package com.atguigu.mall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.mall.seckill.feign.CouponFeignService;
import com.atguigu.mall.seckill.feign.ProductFeignService;
import com.atguigu.mall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.mall.seckill.service.SeckillService;
import com.atguigu.mall.seckill.to.SecKillSkuRedisTo;
import com.atguigu.mall.seckill.vo.SeckillSessionsWithSkus;
import com.atguigu.mall.seckill.vo.SeckillSkuVo;
import com.atguigu.mall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author zststart
 * @create 2022-06-18 21:02
 */
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;
    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus:";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//商品随机码
    @Override
    public void uploadSeckillLatest3Days() {
        //扫描需要参加秒杀的服务
        R session = couponFeignService.getLates3DaySession();
        if(session.getCode() == 0){
            //上架商品
            List<SeckillSessionsWithSkus> data = session.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            //缓存到redis
            //1.缓存活动信息；2.缓存活动的关联商品信息
            saveSessionInfos(data);
            saveSessionSkuInfos(data);
        }
    }
    public List<SecKillSkuRedisTo> blockHandler(BlockException e){
        log.error("getCurrentSeckillSkus被限流了。。");
        return null;
    }
    @SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler")//保护该方法
    @Override
    public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {
        //1、确定当前时间属于哪个秒杀
        long time = new Date().getTime();
        try(Entry entry = SphU.entry("seckillSkus")){//自定义资源名进行熔断降级
            Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            for (String key : keys) {
                String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                Long start = Long.parseLong(s[0]);
                Long end = Long.parseLong(s[1]);
                if (time >= start && time <= end) {
                    //2、获取这个秒杀场次需要的所有商品信息
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<String> list = ops.multiGet(range);
                    if (list != null) {
                        List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
                            SecKillSkuRedisTo redisTo = new SecKillSkuRedisTo();
                            SecKillSkuRedisTo redis = JSON.parseObject((String) item, SecKillSkuRedisTo.class);
//                        redis.setRandomCode(null);
                            return redis;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break;
                }
            }
        }catch (BlockException e){

        }
        //
        return null;
    }
    //获取某个商品秒杀信息
    @Override
    public SecKillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //找到所有需要参与秒杀商品的key
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = ops.keys();
        if(keys!=null && keys.size()>0){
            String regx = "\\d_"+skuId;
            for (String key : keys) {
                if(Pattern.matches(regx,key)){
                    String s = ops.get(key);
                    SecKillSkuRedisTo redisTo = JSON.parseObject(s, SecKillSkuRedisTo.class);
                    //随机码
                    Long startTime = redisTo.getStartTime();
                    long current = new Date().getTime();
                    if(current>=startTime && current<=redisTo.getEndTime()){
                    }else {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String s = ops.get(killId);
        if(StringUtils.isEmpty(s)){
            return null;
        }else {
            SecKillSkuRedisTo redisTo = JSON.parseObject(s, SecKillSkuRedisTo.class);
            //校验合法性
            Long startTime = redisTo.getStartTime();
            Long endTime = redisTo.getEndTime();
            long time = new Date().getTime();
            long ttl = endTime - time;
            if(time>=startTime && time<=endTime){
                //校验随机码和商品id是否正确
                String randomCode = redisTo.getRandomCode();
                String skuId = redisTo.getPromotionSessionId()+"_"+redisTo.getSkuId();
                if(randomCode.equals(key) && killId.equals(skuId)){
                    //验证购物数量是否合理
                    if(num<=redisTo.getSeckillLimit()){
                        //验证这个人是否已经买过，幂等性，只要秒杀过就去redis占位
                        String redisKey = memberRespVo.getId()+"_"+skuId;
                        //场次结束就自动过期
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if(aBoolean){
                            //说明从来没买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                                boolean b = semaphore.tryAcquire(num);
                                //秒杀成功，快速下单，发送mq消息
                                if(b){
                                    String timeId = IdWorker.getTimeId();
                                    SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                    seckillOrderTo.setOrderSn(timeId);
                                    seckillOrderTo.setMemberId(memberRespVo.getId());
                                    seckillOrderTo.setNum(num);
                                    seckillOrderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                                    seckillOrderTo.setSkuId(redisTo.getSkuId());
                                    seckillOrderTo.setSeckillPrice(redisTo.getSeckillPrice());
                                    rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",seckillOrderTo);
                                    return timeId;
                                }
                                return null;
                        }else {
                            return null;
                        }
                    }
                }else{
                    return null;
                }
            }else {
                return null;
            }
        }
        return null;
    }

    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessions){
        if(sessions!=null){
            sessions.stream().forEach(session->{
                Long startTime = session.getStartTime().getTime();
                Long endTime = session.getEndTime().getTime();
                String key = SESSIONS_CACHE_PREFIX + startTime+"_"+endTime;

                Boolean hasKey = redisTemplate.hasKey(key);
                if(!hasKey){
                    List<String> collect = session.getRelationSkus().stream().map(item->item.getPromotionSessionId()+"_"+item.getSkuId().toString()).collect(Collectors.toList());
                    redisTemplate.opsForList().leftPushAll(key,collect);//保存了活动信息
                }

            });
        }
    }
    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessions){
        if(sessions!=null){
            sessions.stream().forEach(session->{
                BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps("SKUKILL_CACHE_PREFIX");
                session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                    //商品的随机码
                    String random = UUID.randomUUID().toString().replace("-", "");
                    if(!ops.hasKey(seckillSkuVo.getPromotionSessionId()+"_"+seckillSkuVo.getSkuId().toString())){
                        SecKillSkuRedisTo secKillSkuRedisTo = new SecKillSkuRedisTo();
                        //sku基本数据，秒杀信息，
                        R r = productFeignService.geSkuinfo(seckillSkuVo.getSkuId());
                        if(r.getCode()==0) {
                            SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                            });
                            secKillSkuRedisTo.setSkuInfo(skuInfo);
                        }
                        BeanUtils.copyProperties(seckillSkuVo,secKillSkuRedisTo);
                        secKillSkuRedisTo.setStartTime(session.getStartTime().getTime());
                        secKillSkuRedisTo.setEndTime(session.getEndTime().getTime());
                        secKillSkuRedisTo.setRandomCode(random);
                        String string = JSON.toJSONString(secKillSkuRedisTo);
                        ops.put(seckillSkuVo.getPromotionSessionId()+"_"+seckillSkuVo.getSkuId().toString(), string);//sku的部分数据

                        //如果当前场次的商品库存信息已经上架，就不需要上架
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + random);
                        semaphore.trySetPermits(seckillSkuVo.getSeckillCount());//可以秒杀的数量作为信号量
                    }
                });
            });
        }

    }
}
